package com.travel.recommend.service.impl;

import com.travel.common.to.AttractionInfoTo;
import com.travel.common.to.UpdateUserAttractionWeightTo;
import com.travel.recommend.entity.UserBehaviorWeightEntity;
import com.travel.recommend.service.UserBehaviorWeightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.common.utils.PageUtils;
import com.travel.common.utils.Query;

import com.travel.recommend.dao.UserAttractionWeightDao;
import com.travel.recommend.entity.UserAttractionWeightEntity;
import com.travel.recommend.service.UserAttractionWeightService;


@Service("userAttractionWeightService")
public class UserAttractionWeightServiceImpl extends ServiceImpl<UserAttractionWeightDao, UserAttractionWeightEntity> implements UserAttractionWeightService {

    @Autowired
    UserBehaviorWeightService userBehaviorWeightService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserAttractionWeightEntity> page = this.page(
                new Query<UserAttractionWeightEntity>().getPage(params),
                new QueryWrapper<UserAttractionWeightEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 更新用户对该景点的权重
     */
    @Override
    public void updateUserAttractionWeight(UpdateUserAttractionWeightTo to,Integer userId) {

        // 判断该用户是否对该景点有权重
        Integer attractionId = to.getAttractionId();
        UserAttractionWeightEntity userAttractionWeightEntity = this.baseMapper.selectOne(new QueryWrapper<UserAttractionWeightEntity>()
                .eq("user_id", userId)
                .eq("attraction_id", attractionId));
        if (userAttractionWeightEntity == null){
            // 无权重，新增
            UserAttractionWeightEntity entity = new UserAttractionWeightEntity();
            entity.setAttractionWeight(to.getWeight());
            entity.setAttractionId(attractionId);
            entity.setUserId(userId);
            entity.setAttractionName(to.getName());
            entity.setAttractionTag(to.getTag());
            entity.setAddTime(new Date());
            entity.setUpdateTime(new Date());
            this.baseMapper.insert(entity);
        }else{
            // 有权重，累加/累减
            Double attractionWeight = userAttractionWeightEntity.getAttractionWeight();
            attractionWeight += to.getWeight();
            userAttractionWeightEntity.setAttractionWeight(attractionWeight);
            this.baseMapper.updateById(userAttractionWeightEntity);
        }

    }

}